/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "mysql_database.h"
#include "node/assert.h"
#include "../sql_delaythread.h"
#include "mysql_connection.h"
using namespace::node::db;

namespace node {
    namespace db {

        bool Database::checkSanity(void)
        {
            return (mysql_thread_safe() != 0);
        }

        MySQLDatabase::MySQLDatabase(void)
        {
            conn_.reset(new MySQLConnection(*this));
            async_conn_.reset(new MySQLConnection(*this));
            delay_thread_.reset(new SqlDelayThread(this, async_conn_.get()));
        }

        MySQLDatabase::~MySQLDatabase(void)
        {

        }

        bool MySQLDatabase::initialize(const ::std::string &host, const ::std::string &port,
            const ::std::string &user, const ::std::string &pass, const ::std::string &db, 
            bool auto_reconnect /*= true*/)
        {
            NODE_ASSERT(conn_ && async_conn_ && delay_thread_);
            return conn_->open(host, port, user, pass, db, auto_reconnect) 
                && async_conn_->open(host, port, user, pass, db, auto_reconnect)
                && delay_thread_->start();
        }

        void MySQLDatabase::close(void)
        {
			NODE_ASSERT(conn_ && async_conn_ && delay_thread_);
            delay_thread_->stop();
            conn_->close();
            conn_.reset();
            async_conn_->close();
            async_conn_.reset();
        }

        void MySQLDatabase::escapeString(::std::string &sql)
        {
            char lsql[MAX_QUERY_LENGTH];
            ::mysql_escape_string(lsql, sql.c_str(), sql.length());
            sql.clear();
            sql = lsql;
        }

        bool MySQLDatabase::reconnect(void)
        {
            return true;
        }

        void MySQLDatabase::ping(void)
        {
			NODE_ASSERT(conn_);
            conn_->ping();
            async_conn_->ping();
        }

    }
}